package jp.co.jalinfotec.sxt.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jp.co.jalinfotec.sxt.form.LoginActionForm;
import jp.co.jalinfotec.sxt.common.Constants;
import jp.co.jalinfotec.sxt.common.SecurityUtil;
import jp.co.jalinfotec.sxt.dto.UserDto;
import jp.co.jalinfotec.sxt.service.UserService;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.factory.annotation.Autowired;

/** Login process */
public class LoginAction extends Action{

	/** User logic */
	@Autowired
	private UserService userService = null;
	
	/**
	 * Login
	 * @param map Mapping information of URL and action
	 * @param form Request parameters
	 * @param request Request object
	 * @param response Response Object
	 */
	@Override
	public ActionForward execute(
			ActionMapping map, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		LoginActionForm loginForm = (LoginActionForm)form;
		
		// Authenticate
		UserDto userInfo = this.authenticate(loginForm.getUserId(), loginForm.getPassword());
		
		// when not authenticated
		if (userInfo.equals(null)){
			ActionMessages errors = new ActionMessages();
			errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("login.error.message"));
			saveErrors(request, errors);
			return map.findForward("error");
		}
		
		// Regenerate session id
		request.getSession(true).invalidate();
			
		// Set user info to the new session.
		HttpSession session = request.getSession(true);
		session.setAttribute(Constants.SESSION_USER_ID, userInfo.getId());
		session.setAttribute(Constants.SESSION_USER_NAME, userInfo.getName());
		return map.findForward("success");
	}
	
	/**
	 * Authenticate user
	 * @param userId User ID
	 * @param password Password
	 * @return When authenticated, return User DTO, otherwise return null.
	 */
	private UserDto authenticate(String userId, String password){
		// Get User DTO
		UserDto dto = this.userService.get(userId);
		// When you couldn't find user DTO, return null .
		if (dto.equals(null)) return null;
		// When password is different from the one user input, return null. 
		if (!SecurityUtil.getHashOfSHA1(password).equals(dto.getPassword())) return null;
		
		return dto;
	}
}
